<template>
  <el-dialog
    :close-on-click-modal="false"
    :visible.sync="visible"
    title="人员字典"
    center
    class="user-dictionary">
      <template>

        <el-form
          class="new-entity-form"
          ref="newEntityForm"
          @submit.native="save()"
          :inline="true"
          :rules="newEntityFormRules"
          :model="newEntityForm">
            <el-form-item label="名称" prop="label">
              <el-input v-model="newEntityForm.label" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="save()">保存</el-button>
            </el-form-item>
        </el-form>

        <el-tabs
          class="user-dictionary-tabs"
          type="border-card"
          v-model="selectedType"
          :before-leave="onTabChange"
          tab-position="left">
            <el-tab-pane
              v-for="(type, typeIndex) in typeList"
              :key="typeIndex"
              :label="type.description"
              :name="type.type">
                <el-table
                  v-if="dictionary[type.type]"
                  :data="dictionary[type.type].filter(x => !search || x.label.toLowerCase().includes(search.toLowerCase()))"
                  height="400px"
                  border>
                    <el-table-column label="序号" type="index" align="center"></el-table-column>
                    <el-table-column label="创建时间" prop="createTime" width="200" align="center"></el-table-column>
                    <el-table-column label="名称" prop="label" width="220" align="center">
                      <template slot="header" slot-scope="scopeHeader">
                        <el-input
                          clearable
                          v-model="search"
                          placeholder="根据名称搜索"/>
                        <span v-if="scopeHeader"></span>
                      </template>
                      <template slot-scope="scope">
                        <el-input
                          v-if="scope.row.isEdit"
                          v-model="scope.row.label"
                          :ref="scope.row.id"
                          @change="editorValChanged(scope.row)"
                          @keyup.enter.native="editorBlur(scope.row)"
                          @blur="update(scope.row)" />
                        <span v-else>{{scope.row.label}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center">
                      <template slot-scope="scope">
                        <el-button type="text" @click="setEdit(scope.row)">编辑</el-button>
                        <el-button type="text" @click="deleteEntity(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
      </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'user-dictionary',
  data () {
    return {
      typeList: [],
      selectedType: '',
      search: '',
      visible: true,
      newEntityForm: {
        label: ''
      },
      newEntityFormRules: {
        label: [{required: true, message: '请填写名称'}]
      }
    }
  },
  methods: {
    async init () {
      this.visible = true
      this.loadTypeList()
    },
    onTabChange (tab) {
      this.selectedType = tab
      this.dispatch()
    },
    editorValChanged (entity) {
      this.$set(entity, 'hasChanged', true)
    },
    async setEdit (entity) {
      let canModify = await this.canModify(entity.id)
      if (canModify) {
        this.$set(entity, 'isEdit', true)
        this.$nextTick(() => {
          this.$refs[entity.id][0].focus()
        })
      } else {
        this.$notify.warning({title: '警告', message: '该字典项已绑定人员，不可修改'})
      }
    },
    editorBlur (entity) {
      this.$refs[entity.id][0].blur()
    },
    async loadTypeList () {
      let res = await this.$http.post('/sys/dict/userlist')
      this.typeList = res.data
      this.selectedType = this.typeList[0].type
      this.dispatch()
    },
    async update (entity) {
      // 判断值是否发生过改变
      if (!entity.hasChanged) {
        entity.hasChanged = false
        entity.isEdit = false
        return
      }

      let res = await this.$http.post(
        '/usercenter-admin/dict/update',
        {
          id: entity.id,
          label: entity.label,
          description: entity.label,
          type: entity.type
        })

      if (res && res.code === 200) {
        this.dispatch()
        entity.hasChanged = false
        this.$notify.success({title: '成功', message: '保存用户字典成功'})
        entity.isEdit = false
      } else {
        this.$notify.error({title: '失败', message: res.msg})
      }
    },
    async save () {
      var valid = await this.$refs.newEntityForm.validate()
      if (!valid) return
      let selectedType = this.selectedType

      let entity = {
        label: this.newEntityForm.label,
        description: this.newEntityForm.label,
        type: selectedType
      }

      let res = await this.$http.post('/usercenter-admin/dict/save', entity)
      if (res && res.code === 200) {
        this.dispatch()
        this.$refs.newEntityForm.resetFields()
        this.$notify.success({title: '成功', message: '新增用户字典成功'})
      } else {
        this.$notify.error({title: '错误', message: res.msg})
      }
    },
    async deleteEntity (entity) {
      let confirm = await this.$confirm('您确认删除当前字典吗？', '提示')
      if (confirm !== 'confirm') return

      let res = await this.$http.post(
        '/usercenter-admin/dict/delete',
        {
          id: entity.id,
          type: entity.type
        })

      if (res && res.code === 200) {
        this.dispatch()
        this.$notify.success({title: '成功', message: '删除用户字典成功'})
      } else {
        this.$notify.error({title: '错误', message: res.msg})
      }
    },
    async canModify (id) {
      let res = await this.$http.post('/usercenter-admin/dict/sysdictitemiscanupdate', {id: id})
      if (res && res.code === 200) {
        return res.data.canUpdate
      }
      return false
    },
    dispatch () {
      let type = this.selectedType
      if (type === 'PROFESSIONAL_TITLE') {
        this.$store.dispatch('user/loadProfessionalTitleList')
      } else if (type === 'EDUCATION') {
        this.$store.dispatch('user/loadEducationList')
      } else if (type === 'DUTY') {
        this.$store.dispatch('user/loadDutyList')
      } else if (type === 'POLITIC_COUNTENANCE') {
        this.$store.dispatch('user/loadPoliticCountenanceList')
      } else if (type === 'CERTTYPE') {
        this.$store.dispatch('user/loadCertTypeList')
      } else if (type === 'PUNISH') {
        this.$store.dispatch('user/loadPunishList')
      }
    }
  },
  computed: {
    dictionary () {
      return {
        POLITIC_COUNTENANCE: JSON.parse(JSON.stringify(this.$store.getters['user/politicCountenanceList'])),
        PROFESSIONAL_TITLE: JSON.parse(JSON.stringify(this.$store.getters['user/professionalTitleList'])),
        EDUCATION: JSON.parse(JSON.stringify(this.$store.getters['user/educationList'])),
        CERTTYPE: JSON.parse(JSON.stringify(this.$store.getters['user/certTypeList'])),
        PUNISH: JSON.parse(JSON.stringify(this.$store.getters['user/punishList'])),
        DUTY: JSON.parse(JSON.stringify(this.$store.getters['user/dutyList']))
      }
    }
  }
}
</script>

<style lang="less">
  .user-dictionary {
    .el-dialog__body {
      padding: 0;
    }

    .new-entity-form {
      padding: 0 20px;
    }

    .user-dictionary-tabs {
      height: 500px;
      border-left: 0;
      border-right: 0;
      border-bottom: 0;

      .tag-group {
        display: flex;
        flex-wrap: wrap;

        .tag-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-right: 12px;
          margin-top: 12px;
          width: 100px;
        }
      }
    }
  }
</style>
